package fr.labri.macchiato.framework.business.encoder;

import java.util.ArrayList;
import java.util.List;

import org.fusesource.restygwt.client.JsonEncoderDecoder;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.smartgwt.client.util.JSON;

import fr.labri.macchiato.framework.business.model.businessEntity.BusinessEntity;
import fr.labri.macchiato.framework.business.model.businessEntity.BusinessEntityFactory;
import fr.labri.macchiato.framework.business.model.businessEntity.Location;
import fr.labri.macchiato.framework.technical.encoder.EncoderGeneric;

/**
 * Class to encode/decode datas from database to/from json format.
 * 
 * @author Michelle AVOMO
 * 
 */
class BusinessEntityEncoder extends EncoderGeneric<BusinessEntity> {
	interface BusinessEntityCodec extends JsonEncoderDecoder<BusinessEntity> {

	}

	/**
	 * Method that encodes in a json format
	 */
	BusinessEntityEncoder() {
		codec = GWT.create(BusinessEntityCodec.class);
	}

	/**
	 * Method that decodes from a json to a sparql format
	 * 
	 */
	@Override
	public List<BusinessEntity> decodeSparqlResult(String jsonString) {
		List<BusinessEntity> results = new ArrayList<BusinessEntity>();

		JSONObject result = new JSONObject(JSON.decode(jsonString));
		result = result.get("results").isObject();

		JSONArray bindings = result.get("bindings").isArray();

		for (int i = 0; i < bindings.size(); i++) {

			String legalName = getAsString(bindings, i, "legalName");

			String logo = getAsString(bindings, i, "depiction");

			String page = getAsString(bindings, i, "page");
			
			String location = getAsString(bindings, i, "location");
			

			BusinessEntity entrySet = BusinessEntityFactory.newBusinessEntity(legalName, logo, page);
			entrySet.addLocation(new Location(location, null));
			results.add(entrySet);
			

		}
		return results;
	}

	/**
	 * Method that RE-encode a result from a json format
	

	private JSONObject recodeJSON(JSONObject object) {
		JSONObject result = new JSONObject();

		for (String key : object.keySet()) {
			JSONString value = new JSONString(object.get(key).isObject()
					.get("value").isString().stringValue());
			result.put(key, value);
		}
		return result;
	} */
}
